// koa-study/src/middleware/validationMiddleware.ts
import { plainToInstance } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';
import { Context, Next } from 'koa';
import Result from '../vo/result';
import { ResultCode } from '../enums/resultCode';

export const validationMiddleware = (type: any) => {
  return async (ctx: Context, next: Next) => {
    if (!ctx.request.body) {
      await next();
      return;
    }
    const input: any = plainToInstance(type, ctx.request.body);
    const errors: ValidationError[] = await validate(input);

    if (errors.length > 0) {
      const msg = Object.values(errors[0].constraints)[0]; // 只需要取第一个错误信息并返回即可
      throw {
        status: 400,
        desc: msg,
      };
    }

    await next();
  };
};